﻿using Contract.WebApi.Application.Commands;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PublicCommon;

namespace Contract.WebApi.Controllers
{
    /// <summary>
    /// 增删改模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ContractController : ControllerBase
    {
        private readonly IMediator mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        public ContractController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 添加货主合同
        /// </summary>
        /// <param name="addContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddHZContractAsync(AddHZContractCommands addContractCommands)
        {
            return Ok(await mediator.Send(addContractCommands));
        }

        /// <summary>
        /// 添加承运合同
        /// </summary>
        /// <param name="addCYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddCYContractAsync(AddCYContractCommands addCYContractCommands)
        {
            return Ok(await mediator.Send(addCYContractCommands));
        }

        /// <summary>
        /// 添加通用合同
        /// </summary>
        /// <param name="addTYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddTYContractAsync(AddTYContractCommands addTYContractCommands)
        {
            return Ok(await mediator.Send(addTYContractCommands));
        }
        
        /// <summary>
        /// 删除货主合同
        /// </summary>
        /// <param name="delHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelHZContractAsync(DelHZContractCommands delHZContractCommands)
        {
            return Ok(await mediator.Send(delHZContractCommands));
        }

        /// <summary>
        /// 删除承运合同
        /// </summary>
        /// <param name="delCYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelCYContractAsync(DelCYContractCommands delCYContractCommands)
        {
            return Ok(await mediator.Send(delCYContractCommands));
        }

        /// <summary>
        /// 删除通用合同
        /// </summary>
        /// <param name="delTYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelTYContractAsync(DelTYContractCommands delTYContractCommands)
        {
            return Ok(await mediator.Send(delTYContractCommands));
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile? file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file selected.");
            }

            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            var allowedExtensions = new[] { ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt" };

            if (!allowedExtensions.Contains(extension))
            {
                return BadRequest("File format not supported.");
            }

            if (file.Length > 20971520) // 20MB
            {
                return BadRequest("File size exceeds limit.");
            }

            var fileName = Path.GetRandomFileName() + extension; // Generate a unique filename
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(new { FileName = fileName });
        }
        //[HttpPost]
        //public async Task<IActionResult> UploadFile(IFormFile? file)
        //{
        //    if (file == null || file.Length == 0)
        //    {
        //        return Content("No file selected.");
        //    }

        //    var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        //    var allowedExtensions = new[] { ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt" };

        //    if (!allowedExtensions.Contains(extension))
        //    {
        //        return Content("File format not supported.");
        //    }

        //    if (file.Length > 20971520) // 20MB
        //    {
        //        return Content("File size exceeds limit.");
        //    }

        //    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", file.FileName);

        //    using (var stream = new FileStream(path, FileMode.Create))
        //    {
        //        await file.CopyToAsync(stream);
        //    }

        //    return Ok(file.FileName);
        //}

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("{fileName}")]
        public IActionResult DownloadFile(string fileName)
        {
            string _rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads");
            var filePath = Path.Combine(_rootPath, fileName);
            if (!System.IO.File.Exists(filePath))
            {
                return NotFound();
            }

            var fileBytes = System.IO.File.ReadAllBytes(filePath);
            var fileMimeType = GetMimeType(fileName);

            return File(fileBytes, fileMimeType, fileName);
        }

        private string GetMimeType(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return extension switch
            {
                ".pdf" => "application/pdf",
                ".doc" => "application/msword",
                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                ".xls" => "application/vnd.ms-excel",
                ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                ".txt" => "text/plain",
                _ => "application/octet-stream" // 默认 MIME 类型
            };
        }

        /// <summary>
        /// 批量删除货主合同
        /// </summary>
        /// <param name="delsHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelsHZContractAsync(DelsHZContractCommands delsHZContractCommands)
        {
            return Ok(await mediator.Send(delsHZContractCommands));
        }

        /// <summary>
        /// 批量删除承运合同
        /// </summary>
        /// <param name="delsCYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelsCYContractAsync(DelsCYContractCommands delsCYContractCommands)
        {
            return Ok(await mediator.Send(delsCYContractCommands));
        }

        /// <summary>
        /// 批量删除通用合同
        /// </summary>
        /// <param name="delsTYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelsTYContractAsync(DelsTYContractCommands delsTYContractCommands)
        {
            return Ok(await mediator.Send(delsTYContractCommands));
        }

        /// <summary>
        /// 修改货主合同
        /// </summary>
        /// <param name="updHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdHZContractAsync(UpdHZContractCommands updHZContractCommands)
        {
            return Ok(await mediator.Send(updHZContractCommands));
        }

        /// <summary>
        /// 修改承运合同
        /// </summary>
        /// <param name="updCYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdCYContractAsync(UpdCYContractCommands updCYContractCommands)
        {
            return Ok(await mediator.Send(updCYContractCommands));
        }

        /// <summary>
        /// 修改通用合同
        /// </summary>
        /// <param name="updTYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdTYContractAsync(UpdTYContractCommands updTYContractCommands)
        {
            return Ok(await mediator.Send(updTYContractCommands));
        }

        /// <summary>
        /// 保存货主草稿
        /// </summary>
        /// <param name="saveHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveHZContractAsync(SaveHZContractCommands saveHZContractCommands)
        {
            return Ok( await mediator.Send(saveHZContractCommands));
        }

        /// <summary>
        /// 保存承运草稿
        /// </summary>
        /// <param name="saveCYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveCYContractAsync(SaveCYContractCommands saveCYContractCommands)
        {
            return Ok(await mediator.Send(saveCYContractCommands));
        }

        /// <summary>
        /// 保存通用草稿
        /// </summary>
        /// <param name="saveTYContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveTYContractAsync(SaveTYContractCommands saveTYContractCommands)
        {
            return Ok(await mediator.Send(saveTYContractCommands));
        }

        /// <summary>
        /// 路线保存
        /// </summary>
        /// <param name="saveCoordinatesCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveCoordinatesAsync(SaveCoordinatesCommands saveCoordinatesCommands)
        {
            return Ok(await mediator.Send(saveCoordinatesCommands));
        }

        /// <summary>
        /// 货主保存后提交
        /// </summary>
        /// <param name="addsHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddsHZContractAsync(AddsHZContractCommands addsHZContractCommands)
        {
            return Ok(await mediator.Send(addsHZContractCommands));
        }

        /// <summary>
        /// 承运保存后提交
        /// </summary>
        /// <param name="addsHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddsCYContractAsync(AddsCYContractCommands addsHZContractCommands)
        {
            return Ok(await mediator.Send(addsHZContractCommands));
        }

        /// <summary>
        /// 通用保存后提交
        /// </summary>
        /// <param name="addsHZContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddsTYContractAsync(AddsTYContractCommands addsHZContractCommands)
        {
            return Ok(await mediator.Send(addsHZContractCommands));
        }

        /// <summary>
        /// 状态修改
        /// </summary>
        /// <param name="alterStateCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AlterStateAsync(AlterStateCommands alterStateCommands)
        {
            return Ok(await mediator.Send(alterStateCommands));
        }

        /// <summary>
        /// 合同列表中提交审批
        /// </summary>
        /// <param name="addedContractCommands"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddedContractAsync(AddedContractCommands addedContractCommands)
        {
            return Ok(await mediator.Send(addedContractCommands));
        }
    }
}
